/**
<p>form控件，用于弹出的单表编辑窗口，底部默认包含保存和关闭按钮</p>
 * xtype = cceafbindingformpanel

 * @module Ext-ux-cceaf-control
 * @class cceaf.control.BindingFormPanel
 * @extends Ext.form.Panel
 * @since 1.0
 */
Ext.define('cceaf.control.BindingFormPanel',{
	extend: 'Ext.form.Panel', 
    alias: 'widget.cceafbindingformpanel',
    requires: [
        'cceaf.ControlDefaultConfig',
        'cceaf.control.Button',
        'cceaf.control.FieldSet'
    ],
    
    /**
	 * 是否有关闭按钮
	 *
     * @property hasClose 
     * @type Boolean
     * @default true
     */
    hasClose: true,
    
    /**
	 * 是否有返回按钮
	 *
     * @property hasBack 
     * @type Boolean
     * @default true
     */
    hasBack: false,
    
	initComponent : function(){
		var config = this;
		
		var layout = config.layout;
		var columns = config.columns;
        if(columns != null){
        	layout = {
	        	type: 'table',
	        	columns: columns
	        };
        	config = Ext.apply(config, {layout: layout});
        }
        
        var operateArea = [],i=0;
		if (config.operateArea) {
			operateArea = config.operateArea;
		} else { //默认操作区
			{
				operateArea[i] = {itemId: 'btnSave', text: '保存', xtype: 'cceafbutton', iconCls: 'saveIcon'};
				i++;
				operateArea[i] = '-';
				i++;
				
				if (config.hasClose) {
					operateArea[i] = {itemId: 'btnClose', text: '关闭', xtype: 'cceafbutton', iconCls: 'closeIcon'};
					i++;
				}
				
				if (config.hasBack) {
					operateArea[i] = {itemId: 'btnBack', text: '返回', xtype: 'cceafbutton', iconCls: 'backIcon'};
					i++;
				}
			}
		}
		
		var defaultFormButtonsAreaHeight = szpshang.Global.DEFAULT_FORM_BUTTONS_AREA_HEIGHT;
		config = Ext.applyIf(config, {
			bodyStyle: 'padding:10px 10px',
	        //anchor: '100% 100%',
	        waitMsgTarget: true,
//	        defaults:{  
//	        	//bodyStyle:'padding:0px 5px 0px 0px',
//    			layout: {
//			        type: 'hbox',
//			        align: 'middle'
//			    },
//    			baseCls:'x-plain',
//    			padding: '5 5 5 5',
//    			xtype:'cceaffieldset'
//            },
	        //buttons: operateArea,
	        dockedItems: [{
	            xtype: 'toolbar',
	            dock: 'bottom',
	            layout: { pack: 'end'},
	            height: defaultFormButtonsAreaHeight,
	            ui: 'footer',
	            items: operateArea
	        }]
		});
		
		if(!config.delDefault){
			config = Ext.applyIf(config, {
		        defaults:{  
	    			layout: {
				        type: 'hbox',
				        align: 'middle'
				    },
	    			baseCls:'x-plain',
	    			padding: '5 5 5 5',
	    			xtype:'cceaffieldset'
	            }
			});
		}
		
		
		cceaf.control.BindingFormPanel.superclass.initComponent.call(this);
	},
	
	initEvents: function() {
    	cceaf.control.BindingFormPanel.superclass.initEvents.call(this);
    	
    	//注册保存按钮事件
    	var btnSave = this.down('#btnSave');
    	if (btnSave) {
			btnSave.on('click',this.page_save);
		}
    	
    	//注册关闭按钮事件
		var btnClose = this.down('#btnClose');
		if (btnClose) {
			btnClose.on('click',this.page_close);
		}
    	
		//注册返回按钮事件
		var btnBack = this.down('#btnBack');
		if (btnBack) {
			btnBack.on('click',this.page_back);
		}
		
    	//注册其他事件
    	this.registerEvent();
    },
    
	
	/**
	 * form的父容器，grid或tree
	 *
     * @property fatherPanel 
     * @type Panel
     * @default null
     */
    fatherPanel: null,
	
	/**
	 * 新增、编辑和删除等操作后，需要更新的组件itemId集合（该组件带有store属性）
	 *
     * @property updatePanelItemIds 
     * @type String 用“,”分割
     * @default null
     */
	updatePanelItemIds: null,
	
	/**
	 * 提交后是否重新载入父对象的stroe
	 *
     * @property storeLoad 
     * @type Boolean
     * @default true
     */
	storeLoad: true,
	
    /**
    * 保存对象
    */
    page_save: function(){
    	var billForm = this.up('cceafbindingformpanel');
    
    	var storeLoad = billForm.storeLoad;
    	
    	var submitParam = {
    		formSubmit: true, //form提交
			closePopWin: true,  //保存数据后关闭窗口
			formLoad: false, //提交数据后不加载form的数据
			storeLoad: storeLoad //提交后加载列表页面的store
    	};
		
		billForm.page_submit(submitParam);
    },
    
    /**
    * 页面数据提交
    * <br> submitParam = {
    * <br> 	formSubmit: false, //false为ajax提交，true为form.submit
    * <br>   actionURL： '',	//提交的action
    * <br>   closePopWin: true, //保存数据后关闭窗口
    * <br>   formLoad: false, //提交数据后重新载入数据
    * <br>   storeLoad: false //提交后是否加载列表页面的store
    * <br> }
    *
    * @param {attribute} submitParam 提交参数
    * @param {Function} callback 回调函数
    */
    page_submit: function(submitParam, callback){
    	var billForm = this;
    	var fatherPanel = billForm.fatherPanel;
		if(fatherPanel == null){
    		cceaf.util.ExtHelper.showErrorDialog('请设置form的fatherPanel！');
    		return;
    	}
		
		var formSubmit = true;
    	var closePopWin = true;
    	var formLoad = false;
    	var storeLoad = true;
    	var actionURL;
    	if(fatherPanel.pageStatus == 'add'){
    		actionURL = fatherPanel.addAction;
    	}
    	else{
    		actionURL = fatherPanel.editAction;
    	}
    	
    	if (submitParam) {
    		if ( Ext.isDefined( submitParam.formSubmit )) {
    			formSubmit = submitParam.formSubmit;
    		}
    		if ( Ext.isDefined( submitParam.actionURL )) {
    			actionURL = submitParam.actionURL;
    		}
    		if ( Ext.isDefined( submitParam.closePopWin )) {
    			closePopWin = submitParam.closePopWin;
    		}
    		if ( Ext.isDefined( submitParam.formLoad )) {
    			formLoad = submitParam.formLoad;
    		}
    		if ( Ext.isDefined( submitParam.storeLoad )) {
    			storeLoad = submitParam.storeLoad;
    		}
    	}
    	
    	if(!billForm.form.isValid()){
    		return;
    	}
    	
    	//校验其他特殊规则，需要重载
    	if(!billForm.checkForm()){
    		return;
    	}
    	
    	//提交数据到服务器
      	if (formSubmit) {
			billForm.form.submit({
	        	url:  actionURL,
	        	waitMsg : '正在保存数据...',
	            success: function(from, action) { 
	            	cceaf.util.ExtHelper.showInfoDialog(action.result.message);
	            	if ( formLoad ) {
	            		billForm.page_load(action);
	            	}
		            	
	            	//var addAndEditWin = Ext.getCmp(billForm.formWindowId);
	            	var addAndEditWin = billForm.findParentByType('window');
	    			if (addAndEditWin) {
	    				if (closePopWin) {
	    					addAndEditWin.close();
	    				}
	    			}  
	    			
	    			if (storeLoad) {
    					//fatherPanel.getStore().load({params:{isquery:true}});
	    				//以上方法不会带入查询条件，以下直接触发查询按钮的click事件
	    				var btnQuery = fatherPanel.down('#btnQuery');
	    				if(btnQuery) {
	    					btnQuery.fireEvent('click');
	    				} else {
	    					fatherPanel.getStore().load({params:{isquery:true}});
	    				}
    					
    					var updatePanelItemIds = billForm.updatePanelItemIds;
    					if (updatePanelItemIds != null) {
    						Ext.Array.each(updatePanelItemIds.split(","), function(updatePanelItemId){
    							//假定updatePanel与fatherPanel在同一级
	    						var updatePanel = fatherPanel.up().down('#' + updatePanelItemId);
	    						if (updatePanel != null && updatePanel.getStore()) {
	    							updatePanel.getStore().load({params:{isquery:true}});
	    						}
	    					});
    					}
    				}
	    			
	    			if ( Ext.isDefined(callback) ) {
	    				callback();
	    			}
	            },
	            failure: function(from, action) {
	            	if(action.result == null) return;
	            	/*
	            	var addAndEditWin = billForm.findParentByType('window');
	    			if (addAndEditWin) {
	    				if (closePopWin) {
	    					addAndEditWin.close();
	    				}
	    			}*/
	    			
	    			cceaf.util.ExtHelper.showErrorDialog(action.result.message); 
	            }
	        });	
	        
	    } else {
	    	//组装主表 JSONString
			var masterJSONData = new Object();
			var formFields = billForm.query('.field');
			
			/* IE不支持
			formFields.forEach(function(item){
				//var itemId = item.getId();
				var itemId = item.getName(); //注意:此处最好用getName,而不用getId
				var itemValue = item.getValue();
				
				if(Ext.isDate(itemValue)){
					itemValue = Ext.Date.format(itemValue,'Y-m-d');
				}
				if (item.getXType() != 'filefield') {
					eval("masterJSONData." + itemId + " = '" + itemValue + "'");
				}
			});
			*/
			var isReturn = false;
	    	Ext.Array.each(formFields, function(item){
				//var itemId = item.getId();
				var itemId = item.getName(); //注意:此处最好用getName,而不用getId
				var itemValue = item.getValue();
				
				if(Ext.isDate(itemValue)){
					itemValue = Ext.Date.format(itemValue,'Y-m-d');
				}
				if (item.getXType() != 'filefield') {
					var splitIndex = itemId.indexOf("-");
					if( splitIndex > 0) {
						//alert(itemId.substr(itemId, splitIndex));
						cceaf.util.ExtHelper.showInfoDialog('必须设置' + itemId.substr(itemId, splitIndex) + '字段的name属性！');
						isReturn = true;
						return;
					}
					eval("masterJSONData." + itemId + " = '" + itemValue + "'");
				}
			});
	    	if (isReturn) {
				return;
			}
	    	
	    	var masterJSONString = Ext.JSON.encode(masterJSONData);
	    	
	    	Ext.MessageBox.wait('正在处理数据...', '提示'); //进度条等待
	      	Ext.Ajax.request({
	      		url:  actionURL,
	      		params: {
	      			masterJSONString: masterJSONString
	      		},
	      		success: function(response){
	      			var isProcessSucess = cceaf.util.ExtHelper.processAjaxRequest(response,true);
	   				
	   				var addAndEditWin = billForm.findParentByType('window');
	    			if (addAndEditWin && isProcessSucess) {
	    				if (closePopWin) {
	    					addAndEditWin.close();
	    				}
	    			}  
	    			
	    			if (storeLoad) { //数据提交后，需要更新查询数据
    					var btnQuery = fatherPanel.down('#btnQuery');
	    				if(btnQuery) {
	    					btnQuery.fireEvent('click');
	    				} else {
	    					fatherPanel.getStore().load({params:{isquery:true}});
	    				}
    				}
	    			
	    			if (callback) {
	    				callback();
	    			}
	   			},
	   			failure: function(response){
	   				cceaf.util.ExtHelper.processAjaxRequest(response,false);
	   			}
	      	});
	      	
	    }
    },
    
    /**
    * 页面提交成功后重新载入
    * 
    * @param {Ext.form.action.Action} action form载入后返回的action数据
    */
    page_load: function(action){
    	billForm = this;
    	
    	var fatherPanel = billForm.fatherPanel;
		if(fatherPanel == null){
    		cceaf.util.ExtHelper.showErrorDialog('请设置form的fatherPanel！');
    		return;
    	}
    	
    	var masterkeys = fatherPanel.masterKeyIds.split(',');
    	var url = fatherPanel.findByKeyAction + '?';
    	
    	for(var i=0;i<masterkeys.length;i++){
			var temp = eval("action.result." + masterkeys[i]);
			url += masterkeys[i] + '=' + temp + '&';
		}
		
		billForm.form.reset();
    	//装载对象到表单
    	billForm.form.load({
	        //waitMsg : '正在载入数据...',
	        url:  url,
    		success: function(form,action) { 
	        	//表单载入数据时,设置特殊值
    			billForm.initEditPage(action);
    			
	        	//显示正确提示
	        	var jsonObject =eval("(" + action.response.responseText + ")");
	        	cceaf.util.ExtHelper.showInfoDialog(jsonObject.message);
	        },
	        failure: function(form,action) {
	        	//显示错误提示
	        	var jsonObject =eval("(" + action.response.responseText + ")");
	        	cceaf.util.ExtHelper.showErrorDialog(jsonObject.message);
	        }
	   	});
    },
    
    /**
    * 根据页面上对象主键加载页面数据
    *
    */
    form_load: function(){
    	billForm = this;
    	var masterkeys = billForm.masterKeyIds.split(',');
    	var url = billForm.findByKeyAction + '?';
    	for(var i=0;i<masterkeys.length;i++){
    		var keyValue = billForm.down('[name=' + masterkeys[i] + ']').getValue();
			url += masterkeys[i] + '=' + keyValue + '&';
		}
		
		billForm.form.reset();
		
    	//装载对象到表单
    	billForm.form.load({
	        //waitMsg : '正在载入数据...',
	        url:  url,
    		success: function(form,action) { 
	        	//表单载入数据时,设置特殊值,包括载入细表数据
	        	billForm.initEditPage(action);
    			
	        	//显示正确提示
	        	var jsonObject =eval("(" + action.response.responseText + ")");
	        	cceaf.util.ExtHelper.showInfoDialog(jsonObject.message);
	        },
	        failure: function(form,action) {
	        	//显示错误提示
	        	var jsonObject =eval("(" + action.response.responseText + ")");
	        	cceaf.util.ExtHelper.showErrorDialog(jsonObject.message);
	        }
	   	});
    },
    
    /**
     * 表单提交后需要重新载入数据后设置form的特殊值
     */
    initEditPage: function(action){
    	
    },
    
    /**
    * 关闭页面
    *
    */
    page_close: function(){
    	var billForm = this.up('cceafbindingformpanel');
    	var addAndEditWin = billForm.findParentByType('window');
 
    	if (addAndEditWin) {
    		addAndEditWin.close();
    	}
    },
    
    /**
     * 返回到查询列表
     *
     */
     page_back: function(){
     	var billForm = this.up('cceafbindingformpanel');
     	var cardPanel = billForm.up('panel');
     	
     	cardPanel.getLayout().setActiveItem(0);
     },
     
    /**
    * form的特殊检验（是否为空的校验根据field的allowBlank属性），默认不校验
    *
    * @return {Boolean} 校验成功范围true
    */
    checkForm: function(){
    	return true;
    },
    
    /**
     * 注册其他事件
     */
    registerEvent: function(){
    	
    },
    
    /**
     * 设置form中field的readonly属性
     * @param {boolean} readOnly 是否只读
     */
    setReadOnly: function(readOnly){
    	var billForm = this;

    	var fields = billForm.query('textfield');
    	Ext.Array.each(fields, function(field){
    		field.setReadOnly(readOnly);
    	});
    }
    
});